package com.easy.util;


import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.springframework.stereotype.Component;

import java.util.Properties;
import java.util.Random;

@Component
public class EmailUtil {
    public static final String FROM = "1803237603@qq.com";
    public static final String AUTH_CODE = "xtnaunxscezzfbif";//授权码
    public static final String HOST = "smtp.qq.com";//邮件服务器
    public static final String PORT = "465";//端口

    private static final Session session;
    static {
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", HOST);//邮件服务器
        props.setProperty("mail.smtp.port", PORT);//端口
        props.setProperty("mail.smtp.auth", "true");//验证
        props.setProperty("mail.smtp.ssl.enable", "true");//启用SSL
        session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM, AUTH_CODE);
            }
        });
        // 开启调试模式
        session.setDebug(true);
    }

    public static void sendEmail(String to, String text) {
        Message message = new MimeMessage(session);
        try {
            message.addFrom(new Address[]{new InternetAddress(FROM)});
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("医约小旋风");
            message.setContent("<h1 style='color:red'>验证码:"+text+"</h1>"
                    , "text/html;charset=utf-8");
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    // 生成验证码并发送邮件
    public static String generateAndSendCode(String to) {
        // 生成6位随机验证码
        String code = String.format("%06d", new Random().nextInt(1000000));
        sendEmail(to, code);  // 发送验证码
        return code;
    }

//    public static void main(String[] args) {
//        sendEmail("1803237603@qq.com", "123456");
//    }
}
